package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.task.AmqpConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.zzyl.common.constant.CacheConstants.IOT_DEVICE_LAST_DATA;

/**
 * 设备数据上报Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-18
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService, AmqpConsumer
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据上报
     * 
     * @param id 设备数据上报主键
     * @return 设备数据上报
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据上报列表
     * 
     * @param deviceData 设备数据上报
     * @return 设备数据上报
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据上报
     * 
     * @param deviceData 设备数据上报
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据上报
     * 
     * @param deviceData 设备数据上报
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据上报
     * 
     * @param ids 需要删除的设备数据上报主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据上报信息
     * 
     * @param id 设备数据上报主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量新增设备上报的数据
     *
     * @param notifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData notifyData) {
        // 1、根据设备ID查询设备信息
        String deviceId = notifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));

        // 2、判断设备是否存在
        if(ObjectUtil.isNull(device)){
            log.error("设备不存在，iotId = {}", deviceId);
            return;
        }

        // 3、获取设备上报的数据，保存到数据库（一个设备可以有多个services）
        List<IotMsgService> services = notifyData.getBody().getServices();
        try {
            for (IotMsgService service : services) {
                Map<String, Object> properties = service.getProperties();
                if(ObjectUtil.isEmpty(properties)){
                    continue;
                }

                // 3.1、处理上报时间
                LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
                LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();

                // 3.2、处理上报属性数据
                List<DeviceData> deviceDataList = new ArrayList<>(properties.size());
                properties.forEach((key,value) -> {
                    DeviceData deviceData = DeviceData.builder()
                            .iotId(deviceId)
                            .functionId(key)
                            .dataValue(value.toString())
                            .alarmTime(alarmTime)
                            .accessLocation(device.getRemark())
                            .build();
                    BeanUtil.copyProperties(device, deviceData,"id","createBy","updateBy","createTime","updateTime");
                    deviceDataList.add(deviceData);
                });

                // 3.2.1、批量保存至数据库
                this.saveBatch(deviceDataList);

                // 3.2.2、将该设备最新上报数据保存至redis，供后续查询智能床位数据使用（Hash   iot:device_last_data    deviceId  List<DeviceData> ）
                redisTemplate.opsForHash().put(IOT_DEVICE_LAST_DATA, deviceId, deviceDataList);
            }
        } catch (Exception e) {
            log.error("设备数据上报异常，{}", e.getMessage());
        }
    }

    @Override
    public void consumer(IotMsgNotifyData notifyData) {
        batchInsertDeviceData(notifyData);
    }
}
